<template>
  <div class="app-container">
    <el-form
      :inline="true"
      :model="filters"
      class="demo-form-inline filter-container"
      ref="refForm"
    >
      <el-form-item label="标题：" prop="title">
        <el-input v-model="filters.title" @keyup.enter.native="submitFilterForm"></el-input>
      </el-form-item>
      <el-form-item label="会员层级" prop="memberLevelId">
        <el-select
          v-model="filters.memberLevelId"
          placeholder="请选择会员层级"
          :collapse-tags="true"
          :multiple="true"
        >
          <el-option
            v-for="item in levelList"
            :key="item.levelId"
            :label="item.name"
            :value="item.levelId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="会员账号:" prop="memberAccount">
        <el-input v-model="filters.memberAccount" @keyup.enter.native="submitFilterForm"></el-input>
      </el-form-item>
      <el-form-item label="状态:" prop="state">
        <el-select v-model="filters.state">
          <el-option
            v-for="item in consts.POST_STATUS"
            :key="item.value"
            :label="item.title"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="最后编辑:" prop="lastOperator">
        <el-input v-model="filters.lastOperator" @keyup.enter.native="submitFilterForm"></el-input>
      </el-form-item>
      <el-form-item label="发送时间：" prop="time">
        <el-date-picker
          v-model="filters.time"
          class="filter-item"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
          value-format="yyyy-MM-dd HH:mm:ss"
          align="left"
        ></el-date-picker>
      </el-form-item>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="submitFilterForm"
      >搜索</el-button>
      <el-button @click="selfResetForm('refForm')">重置</el-button>
    </el-form>

    <el-button
      v-if="roleCheck('send-add')"
      type="primary"
      style="margin:10px 0"
      @click="openDialog({dialogName: 'add-notice-letter',props: {}})"
    >新建站内信</el-button>

    <el-table
      :data="tableData.list"
      v-loading="loading"
      element-loading-text="给我一点时间"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column label="标题" align="center">
        <template slot-scope="{row}">
          <span class="text-nowrap">{{row.title}}</span>
        </template>
      </el-table-column>
      <el-table-column label="发布时间" align="center">
        <template slot-scope="{row}">
          <span class="text-nowrap">{{row.sendTime | toTime}}</span>
        </template>
      </el-table-column>
      <el-table-column label="会员层级" align="center">
        <template slot-scope="{row}">
          <span
            class="text-tips text-nowrap"
            @click="openDialog({dialogName: 'check-tips',props: {content:row.memberLevelName,title:'会员层级'}})"
          >{{row.memberLevelName}}</span>
        </template>
      </el-table-column>
      <el-table-column label="会员账号" align="center">
        <template slot-scope="{row}">
          <span
            class="text-tips text-nowrap"
            @click="openDialog({dialogName: 'check-tips',props: {content:row.memberAccount,title:'会员账号'}})"
          >{{row.memberAccount}}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后编辑" align="center">
        <template slot-scope="{row}">{{row.lastOperator}}</template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="{row}">{{row.state | toConverter('POST_STATUS')}}</template>
      </el-table-column>
       <el-table-column label="会员未读人数" align="center">
        <template slot-scope="{row}">
          <span
            class="undeline-link"
            @click="openDialog({dialogName: 'check-isread-member',props: row})"
          >{{row.isReadCount}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="300px">
        <template slot-scope="{row}">
          <el-button
            v-if="roleCheck('send-check') && row.state !== 0"
            type="text"
            @click="openDialog({dialogName: 'check-notice-letter',props: row})"
          >查看</el-button>
          <el-button
            v-if="roleCheck('send-edit') && row.state === 0"
            @click="openDialog({dialogName: 'add-notice-letter',props: {row,levelList,id:row.id}})"
            type="text"
          >编辑</el-button>
          <el-button
            v-if="roleCheck('send-del') && row.state === 0"
            type="text"
            @click="handleDelete(row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="gridSizeChange"
        @current-change="gridCurrentChange"
        :current-page="filters.page"
        :page-sizes="gridPageSize"
        :page-size="filters.size"
        :layout="gridLayout"
        :total="tableData.total"
      ></el-pagination>
    </div>
    <add-notice-letter
      v-if="dialogName === 'add-notice-letter'"
      v-model="dialogVisible"
      :row-data="dialogProps"
      :id="dialogProps.id"
      @submit="submitFinished"
    />
    <check-notice-letter
      v-if="dialogName === 'check-notice-letter'"
      v-model="dialogVisible"
      :row-data="dialogProps"
      :id="dialogProps.id"
      @submit="submitFinished"
    />
    <check-isread-member
      v-if="dialogName === 'check-isread-member'"
      v-model="dialogVisible"
      :row-data="dialogProps"
      :id="dialogProps.id"
      @submit="submitFinished"
    />
    <check-tips
      v-if="dialogName === 'check-tips'"
      v-model="dialogVisible"
      :row-data="dialogProps"
    />
  </div>
</template>

<script>
import {
  form, grid, dialog, resetForm,
} from '@/build';
import {
  noticePostBoxManageListApi,
  noticeLetterDeleteApi,
} from '@/services/api/notice';
import { getUserLevelList } from '@/services/api/userLevel';
import AddNoticeLetter from './addNoticeLetter.vue';
import CheckNoticeLetter from './checkNoticeLetter';
import CheckIsreadMember from './checkIsreadMember';
import CheckTips from '../preview/checkTips';

export default {
  name: 'post-box',

  mixins: [form, grid, dialog, resetForm],

  components: {
    AddNoticeLetter,
    CheckNoticeLetter,
    CheckIsreadMember,
    CheckTips,
  },

  props: {},

  data() {
    return {
      operatorList: [],
      levelList: [],
      tableData: {
        list: [],
        total: 0,
      },
      // form: {},
      filters: {
        memberLevelId: undefined, // 会员层级
        memberLevelName: undefined, // 会员层级名称
        memberAccount: undefined, // 会员账户
        title: undefined, // 标题
        state: undefined, // 状态
        time: [
          moment().format('YYYY-MM-DD 00:00:00'),
          moment().format('YYYY-MM-DD 23:59:59'),
        ],
        lastOperator: undefined, // 最后编辑
        beginTime: undefined, // 开始时间
        endTime: undefined, // 结束时间
        page: 1,
        size: 20,
      },
      filterDateType: false,
    };
  },

  methods: {
    handleDelete({ id }) {
      this.$confirm('确定要删除此公告吗？', '删除公告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          noticeLetterDeleteApi({
            id: String(id),
          }).then(([result, data]) => {
            if (result) {
              this.doGet({ action: 'getGrid' });
              this.$message({
                type: 'success',
                message: '删除成功!',
              });
            } else {
              this.$message({
                type: 'error',
                message: `删除失败!${data.message}`,
              });
            }
          });
        })
        .catch(() => {});
    },
    selfResetForm(formName) {
      this.resetForm(formName);
      this.submitFilterForm();
    },
    submitFilterForm() {
      // let { time, memberLevelId, memberLevelName } = this.filters;
      // let beginTime;
      // let endTime;
      // const obj = {};
      // if (!_.isUndefined(time) && _.isArray(time)) {
      //   beginTime = time[0];
      //   endTime = time[1];
      // }
      // if (memberLevelId.length) {
      //   memberLevelId.map((item) => {
      //     this.levelList.map((_item) => {
      //       if (item === _item.levelId) {
      //         obj[item] = _item.name;
      //       }
      //       return obj;
      //     });
      //   });
      //   memberLevelName = Object.values(obj).join(',');
      // } else {
      //   memberLevelName = undefined;
      // }
      // this.filters = {
      //   ...this.filters, beginTime, endTime, memberLevelName,
      // };
      this.gridSearch();
    },
  },

  mounted() {
    this.bindGet(noticePostBoxManageListApi, 'tableData', {
      action: 'getGrid',
      sendingData: 'filters',
      beforeSend: (data) => {
        let { time, memberLevelId, memberLevelName } = data;
        let beginTime;
        let endTime;
        const obj = {};
        if (!_.isUndefined(time) && _.isArray(time)) {
          beginTime = time[0];
          endTime = time[1];
        }
        if (memberLevelId && memberLevelId.length) {
          memberLevelId.map((item) => {
            this.levelList.map((_item) => {
              if (item === _item.levelId) {
                obj[item] = _item.name;
              }
              return obj;
            });
          });
          memberLevelName = Object.values(obj).join(',');
        } else {
          memberLevelName = undefined;
        }
        return {
          ...data, beginTime, endTime, memberLevelName,
        };
      },
    });
    // 获取会员层级列表
    this.bindGet(getUserLevelList, 'levelList', {});
    this.getAll();
  },
};
</script>
<style lang="scss" scoped>
.image {
  width: 100px;
  height: 100px;
}
.el-col {
  border-radius: 4px;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.undeline-link {
  display: block;
  text-align: center;
  text-decoration: underline;
  cursor: pointer;
  color: blue;
}
.text-tips {
  color: blue;
  cursor: pointer;
}
</style>
